﻿using AutoWinUI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Windows.Automation;

namespace TestProject1
{
    
    
    /// <summary>
    ///This is a test class for DesktopTest and is intended
    ///to contain all DesktopTest Unit Tests
    ///</summary>
    [TestClass()]
    public class DesktopTest
    {


        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        // 
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion


        /// <summary>
        ///A test for ClickStartButton
        ///</summary>
        [TestMethod()]
        public void ClickStartButtonTest()
        {
            // run action. click start button
            AutoWinUI.Desktop.ClickStartButton();

            System.Threading.Thread.Sleep(1000);

            // check if open 
            bool answer = true;
            AutomationElement Desktop = AutomationElement.RootElement;
            AutomationElement SearchProgram = null;
            PropertyCondition SearchProgramAutomationID = new PropertyCondition(AutomationElement.AutomationIdProperty, "");
            PropertyCondition SearchProgramClassName = new PropertyCondition(AutomationElement.ClassNameProperty, "DV2ControlHost");
            AndCondition and1 = new AndCondition(SearchProgramClassName, SearchProgramAutomationID);
            SearchProgram = Desktop.FindFirst(TreeScope.Children, and1);
            if (SearchProgram == null)
                answer = false;
            else
                answer = true;

            System.Threading.Thread.Sleep(1000);
            // click again to be back
            //AutoWinUI.Desktop.ClickStartButton();

            // do assert
            Assert.AreEqual(true, answer, "Desktop - Start Button");      
        }

        /// <summary>
        ///A test for FindTaskBar
        ///</summary>
        [TestMethod()]
        [DeploymentItem("AutoWinUIComponent.dll")]
        public void FindTaskBarTest()
        {
            //AutomationElement expected = null; // TODO: Initialize to an appropriate value
            //AutomationElement actual;
            //actual = Desktop_Accessor.FindTaskBar();
            //Assert.AreEqual(expected, actual);
            //Assert.Inconclusive("Verify the correctness of this test method.");
        }

        /// <summary>
        ///A test for LaunchProgram
        ///</summary>
        [TestMethod()]
        public void LaunchProgramTest()
        {
            AutoWinUI.Desktop.LaunchProgram("inetcpl.cpl");

            bool answer = false;

            System.Threading.Thread.Sleep(10000);

            //find "Internet Options" existing on the desktop
            AutomationElement Desktop = AutomationElement.RootElement;
            AutomationElement InternetOptions = null;
            PropertyCondition inetcplAutomationID = new PropertyCondition(AutomationElement.AutomationIdProperty, "");
            PropertyCondition inetcplClassName = new PropertyCondition(AutomationElement.ClassNameProperty, "#32770");
            AndCondition and1 = new AndCondition(inetcplAutomationID, inetcplClassName);
            InternetOptions = Desktop.FindFirst(TreeScope.Children, and1);
            if (InternetOptions == null)
            {
                answer = false;
                AutomationElement SearchResult = null;
                PropertyCondition SearchResultAutomationID = new PropertyCondition(AutomationElement.AutomationIdProperty, "");
                PropertyCondition SearchResultClassName = new PropertyCondition(AutomationElement.ClassNameProperty, "CabinetWClass");
                AndCondition and3 = new AndCondition(SearchResultAutomationID, SearchResultClassName);
                SearchResult = Desktop.FindFirst(TreeScope.Children, and3);
                AutomationElement CloselButton = null;
                PropertyCondition CloselButtonAutomationID = new PropertyCondition(AutomationElement.AutomationIdProperty, "Close");
                PropertyCondition CloselButtonClassName = new PropertyCondition(AutomationElement.ClassNameProperty, "");
                AndCondition and4 = new AndCondition(CloselButtonAutomationID, CloselButtonClassName);
                CloselButton = SearchResult.FindFirst(TreeScope.Descendants, and4);
                InvokePattern pat1 = (InvokePattern)CloselButton.GetCurrentPattern(InvokePattern.Pattern);
                pat1.Invoke();

            }
            else
            {
                answer = true;
                AutomationElement CancelButton = null;
                PropertyCondition CancelAutomationID = new PropertyCondition(AutomationElement.AutomationIdProperty, "2");
                PropertyCondition CancelClassName = new PropertyCondition(AutomationElement.ClassNameProperty, "Button");
                AndCondition and2 = new AndCondition(CancelAutomationID, CancelClassName);
                CancelButton = InternetOptions.FindFirst(TreeScope.Children, and2);
                InvokePattern pat1 = (InvokePattern)CancelButton.GetCurrentPattern(InvokePattern.Pattern);
                pat1.Invoke();
            }

            // do assertion
            Assert.AreEqual(true, answer);
        }

        /// <summary>
        ///A test for ShowDesktop
        ///</summary>
        [TestMethod()]
        public void ShowDesktopTest()
        {
 
            // click show desktop
            try
            {
                CommonUtility.KillProcess("notepad");
                CommonUtility.WriteLog("kill notepad");

                //Launch NotePad
                CommonUtility.StartProcess("c:\\windows\\notepad.exe");
                CommonUtility.WriteLog("notepad is launched");
                CommonUtility.Sleep(1);

                //run ShowDesktop 
                AutoWinUI.Desktop.ShowDesktop();
                CommonUtility.WriteLog("ShowDesktop is invoked");

                CommonUtility.Sleep(30);

                //CommonUtility.StartProcess("c:\\windows\\notepad.exe");

                //get all elements on desktop 
                AutomationElement Desktop = AutomationElement.RootElement;
                AutomationElementCollection aec = Desktop.FindAll(TreeScope.Subtree, Condition.TrueCondition);
                CommonUtility.WriteLog("collection count = " + aec.Count.ToString());
                //check IsOffScreen property. all of them should be true
                int wincount = 0;

                CommonUtility.Sleep(1);

                foreach (AutomationElement e in aec)
                {
                    //study later from here 
                    //CommonUtility.WriteLog("element name= " + e.Current.Name);

    //                if (e.Current.ProcessId == 0 || e.Current.ProcessId == 4)
    //                    continue;
    //                //skip explorer process , this will skip default desktop explorer
    //                if (e.Current.ClassName.ToLower().Trim() == "shell_traywnd")
    //                    continue;
    //                //skip windows with no Main UI   
    //                if (e.Current.NativeWindowHandle == 0)
    //                    continue;
    //                //skip windows in system tray  
    //                if (e.Current.AutomationId.ToLower().Trim() == "systemtray")
    //                    continue;
                    if (string.IsNullOrEmpty(e.Current.Name))
                        continue;
                    if (e.Current.Name.ToLower().Contains("autowinui"))
                        continue;
                    if (string.IsNullOrEmpty(e.Current.ControlType.ProgrammaticName))
                        continue;

                    if (e.Current.ControlType.ProgrammaticName.ToLower().Trim().Contains("window")
                        // ||  e.Current.ControlType.ProgrammaticName.ToLower().Trim().Contains("dialog") 
                        // || e.Current.ControlType.ProgrammaticName.ToLower().Trim().Contains("pane")
                        )
                    {
                        if (e.Current.IsOffscreen)
                        {
                            // the app is minimized
                            //CommonUtility.WriteLog("name=" + e.Current.Name + " is minimized");
                        }
                        else
                        {
                            // the app is not minimized
                            CommonUtility.WriteLog("name= " + e.Current.Name + " is NOT miniized , classname=" + e.Current.ClassName);
                            wincount++;
                        }
                    }                      
                }

                CommonUtility.Sleep(1);

                //restore Desktop
                AutoWinUI.Desktop.ShowDesktop();
                CommonUtility.WriteLog("run ShowDesktop() again");

                //shutdown NotePad
                CommonUtility.KillProcess("notepad");
                CommonUtility.WriteLog("kill notepad");

                CommonUtility.Sleep(1);

                //if all are true, assert Pass, otherwise, assert Fail
                CommonUtility.WriteLog("wincount= " + wincount);
                int target = 0;
                Assert.AreEqual(target, wincount);

            }
            catch (Exception ex)
            {
                CommonUtility.WriteLog("exception = " + ex.Message);
            }
          
        }
    }
}
